package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import beans.AlgorithmDetail;
import db.DBDruidManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class PublicDao {
	@Autowired
	AlgorithmDao algorithmDao;
    public JSONArray packAlgorithmDetail(JSONArray inputArray, String user){
        JSONArray outputArray = new JSONArray();
        for(int s=0;s<inputArray.size();s++){
            String frontId=inputArray.getJSONObject(s).getString("algorithmId");
            AlgorithmDetail frontAlgorithmDetail = algorithmDao.getAlgorithmDetail(frontId,user);
            JSONObject algorithmObject = JSONObject.fromObject(frontAlgorithmDetail);
            if(algorithmObject.toString()!=null){
                algorithmObject.put("blockId",inputArray.getJSONObject(s).getString("blockId"));
                algorithmObject.put("blockName",inputArray.getJSONObject(s).getString("blockName"));
            }else{
                algorithmObject.put("blockId","");
                algorithmObject.put("blockName","");
            }
            outputArray.add(algorithmObject);
        }
        return outputArray;
    }
    public static synchronized int oneNum(String sql,Object[] params){
        int num = (int) Query.executeQueryObject(sql, params, new QueryCallBack() {

            @Override
            public Object doExecute(ResultSet rs) {
                int num = 0;
                try {
                    while (rs.next()) {
                        num = rs.getInt(1);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return num;
            }
        });
        return num;
    }

    public static List<Object> generateKeys(List<Object> results, String insertSql, Object[] params){
        return Query.executeDMLwithGeneratedKeys(results, insertSql, params, new QueryCallBackList() {
            @Override
            public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
                try {
                    while (rs.next()) {
                        results.add(Integer.valueOf(rs.getInt(1)));
                    }
                    return results;
                } catch (SQLException e) {
                    e.printStackTrace();
                    return null;
                }
            }
        });
    }
}

